package com.bwt.usermanage;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.provider.Settings;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.bwt.usermanage.Entity.User;
import com.bwt.usermanage.Mapper.UserDao;
import com.bwt.usermanage.utils.*;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.cityjd.JDCityConfig;
import com.lljjcoder.style.cityjd.JDCityPicker;
import com.lljjcoder.style.citylist.Toast.ToastUtils;
import com.lljjcoder.style.citypickerview.CityPickerView;
import org.apache.commons.lang3.StringUtils;


import java.util.Calendar;
import java.util.Locale;

import static com.bwt.usermanage.utils.DialogUtil.showDatePicker;
import static com.bwt.usermanage.utils.PermissionUtils.MY_PERMISSIONS_REQUEST_CALL_PHONE;

public class InsertOrEditActivity extends AppCompatActivity implements View.OnClickListener, View.OnLongClickListener {

    //申明对象
    CityPickerView mPicker=new CityPickerView();

    private ActivityResultLauncher<Intent> mResultLauncher;
    private EditText et_borrowerPhone;
    private EditText et_BorrowerName;
    private EditText et_borrowerSFZ;
    private TextView tv_borrowerHJAddress;
    private TextView tv_borrowerSFZEndTime;
    private TextView tv_uid;
    private TextView tv_title;
    private RadioGroup rg_borrowerSex;
    private RadioGroup rg_borrowerHJType;
    private EditText et_spouseSFZ;
    private EditText et_suretyAge;
    private EditText et_suretySFZ;
    private EditText et_spouseName;
    private EditText et_suretyName;
    private TextView tv_guaranteeAddress;
    private EditText et_guaranteeArea;
    private EditText et_guaranteeCommoner;
    private EditText et_guaranteeYear;
    private Spinner sp_guaranteeType;
    private EditText et_guaranteeQIUQUANHAO;
    private EditText et_realEstateZJH;
    private EditText et_pledgeNum;
    private EditText et_evaluationPrice;
    private EditText et_companyName;
    private Spinner sp_companyType;
    private EditText et_loansPrice;
    private EditText et_loansRate;
    private TextView tv_companyAddress;
    private EditText et_remark;
    private EditText et_guaranteeAddressDetail;
    private EditText et_companyAddressDetail;
    private TextView tv_creditTime;
    private TextView tv_grantTime;
    private TextView tv_expireTime;
    private Button btn_save;
    private Button btn_navigation;
    private Button btn_navigation2;
    private Button btn_borrowerProfilePic;
    private ImageView iv_borrowerProfilePic;
    private ImageView iv_back;
    private LinearLayout ll_guaranteeAddress;
    private LinearLayout ll_companyAddress;
    private UserDao userDao;
    private PermissionUtils permissionUtils;
    private JDCityPicker cityPicker;


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_CALL_PHONE: // 拨打电话
                if (permissionUtils.checkGranted(grantResults)) {
                    call();
                } else {
                    ToastUtil.show(this, "获取拨打电话权限失败");
                    jumptosetting();
                }
                break;
        }

    }

    private void jumptosetting() {

        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.fromParts("package", getPackageName(), null));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_insert_or_edit);

        initView();


        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            int uid = bundle.getInt("uid");
            loadData(uid);
        }

        // 跳转相册,选择图片 返回
        mResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == RESULT_OK) {
                    Intent intent = result.getData();

                    Uri picUri = intent.getData();
                    if (picUri != null) {

                        iv_borrowerProfilePic.setImageURI(picUri);
                        Log.d("add_pri", "picUri : " + picUri);
                    }
                }
            }
        });
    }

    private void initView() {
        userDao = AppDatabase.getInstance(this).userDao();
        permissionUtils = PermissionUtils.getInstance(this);

        btn_borrowerProfilePic = findViewById(R.id.btn_borrowerProfilePic);
        tv_title = findViewById(R.id.tv_title);
        iv_back = findViewById(R.id.iv_back);
        iv_borrowerProfilePic = findViewById(R.id.iv_borrowerProfilePic);
        et_BorrowerName = findViewById(R.id.et_BorrowerName);
        et_borrowerPhone = findViewById(R.id.et_borrowerPhone);
        et_borrowerSFZ = findViewById(R.id.et_borrowerSFZ);
        tv_borrowerHJAddress = findViewById(R.id.tv_borrowerHJAddress);
        et_spouseSFZ = findViewById(R.id.et_spouseSFZ);
        et_suretyAge = findViewById(R.id.et_suretyAge);
        et_suretySFZ = findViewById(R.id.et_suretySFZ);
        et_spouseName = findViewById(R.id.et_spouseName);
        et_suretyName = findViewById(R.id.et_suretyName);
        tv_guaranteeAddress = findViewById(R.id.tv_guaranteeAddress);
        et_guaranteeArea = findViewById(R.id.et_guaranteeArea);
        et_guaranteeCommoner = findViewById(R.id.et_guaranteeCommoner);
        et_guaranteeYear = findViewById(R.id.et_guaranteeYear);
        sp_guaranteeType = findViewById(R.id.sp_guaranteeType);
        et_guaranteeQIUQUANHAO = findViewById(R.id.et_guaranteeQIUQUANHAO);
        et_realEstateZJH = findViewById(R.id.et_realEstateZJH);
        et_pledgeNum = findViewById(R.id.et_pledgeNum);
        et_evaluationPrice = findViewById(R.id.et_evaluationPrice);
        et_companyName = findViewById(R.id.et_companyName);
        sp_companyType = findViewById(R.id.sp_companyType);
        et_loansPrice = findViewById(R.id.et_loansPrice);
        et_loansRate = findViewById(R.id.et_loansRate);
        tv_companyAddress = findViewById(R.id.tv_companyAddress);
        et_remark = findViewById(R.id.et_remark);
        et_companyAddressDetail = findViewById(R.id.et_companyAddressDetail);
        et_guaranteeAddressDetail = findViewById(R.id.et_guaranteeAddressDetail);

        rg_borrowerSex = findViewById(R.id.rg_borrowerSex);
        rg_borrowerHJType = findViewById(R.id.rg_borrowerHJType);


        tv_borrowerSFZEndTime = findViewById(R.id.tv_borrowerSFZEndTime);
        tv_creditTime = findViewById(R.id.tv_creditTime);
        tv_grantTime = findViewById(R.id.tv_grantTime);
        tv_expireTime = findViewById(R.id.tv_expireTime);
        btn_save = findViewById(R.id.btn_save);
        btn_navigation = findViewById(R.id.btn_navigation);
        btn_navigation2 = findViewById(R.id.btn_navigation2);
        tv_uid = findViewById(R.id.tv_uid);

        btn_borrowerProfilePic.setOnClickListener(this);
        iv_borrowerProfilePic.setOnClickListener(this);
        tv_borrowerSFZEndTime.setOnClickListener(this);
        tv_creditTime.setOnClickListener(this);
        tv_grantTime.setOnClickListener(this);
        tv_expireTime.setOnClickListener(this);
        btn_save.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        tv_borrowerHJAddress.setOnClickListener(this);
        tv_guaranteeAddress.setOnClickListener(this);
        tv_companyAddress.setOnClickListener(this);
        btn_navigation.setOnClickListener(this);
        btn_navigation2.setOnClickListener(this);


        et_borrowerPhone.setOnLongClickListener(this);

        et_borrowerPhone.addTextChangedListener(new HideTextWatcher(this, et_borrowerPhone, 11));
        et_borrowerSFZ.addTextChangedListener(new HideTextWatcher(this, et_borrowerSFZ, 18));
        et_spouseSFZ.addTextChangedListener(new HideTextWatcher(this, et_borrowerSFZ, 18));
        et_suretyAge.addTextChangedListener(new HideTextWatcher(this, et_borrowerSFZ, 3));
        et_suretySFZ.addTextChangedListener(new HideTextWatcher(this, et_borrowerSFZ, 18));
    }

    private void call() {
        Intent Intent = new Intent(android.content.Intent.ACTION_CALL, Uri.parse("tel:" + et_borrowerPhone.getText().toString()));
        startActivity(Intent);
    }

    private void loadData(int uid) {
        tv_title.setText("编辑用户");
        User user = userDao.findUserById(uid);
        if (user == null) {
            ToastUtil.show(this, "系统异常!");
            finish();
        }
        et_BorrowerName.setText(user.borrowerName);
        boolean f = DateUtil.todayCompare(user.expireTime);
        if (f) {
            TextView tv_expire = findViewById(R.id.tv_expire);
            tv_expire.setVisibility(View.VISIBLE);
            et_BorrowerName.setTextColor(getResources().getColor(R.color.colorAccent));
        }

        if (StringUtils.isNotBlank(user.borrowerProfilePic)) {
            Bitmap bitmap = BitmapFactory.decodeFile(user.borrowerProfilePic);
            iv_borrowerProfilePic.setImageBitmap(bitmap);
        }

        ViewUtil.setRadioGroup(user.borrowerSex, rg_borrowerSex, R.id.btnMan, R.id.btnWoman);

        et_borrowerPhone.setText(user.borrowerPhone);
        et_borrowerSFZ.setText(user.borrowerSFZ);
        tv_borrowerSFZEndTime.setText(user.borrowerSFZEndTime);
        tv_borrowerHJAddress.setText(user.borrowerHJAddress);
        ViewUtil.setRadioGroup(user.borrowerHJType, rg_borrowerHJType, R.id.btn_village, R.id.btn_city, R.id.btn_other);

        et_spouseName.setText(user.spouseName);
        et_spouseSFZ.setText(user.spouseSFZ);
        et_suretyName.setText(user.suretyName);
        et_suretyAge.setText(user.suretyAge);
        et_suretySFZ.setText(user.suretySFZ);
        tv_guaranteeAddress.setText(user.guaranteeAddress);
        et_guaranteeAddressDetail.setText(user.guaranteeAddressDetail);
        et_guaranteeArea.setText(user.guaranteeArea);
        et_guaranteeCommoner.setText(user.guaranteeCommoner);
        et_guaranteeYear.setText(user.guaranteeYear);
        ViewUtil.setSpinnerSlection(user.guaranteeType, getResources().getStringArray(R.array.sp_guaranteeTypes), sp_guaranteeType);
        et_guaranteeQIUQUANHAO.setText(user.guaranteeQIUQUANHAO);
        et_realEstateZJH.setText(user.realEstateZJH);

        tv_creditTime.setText(user.creditTime);
        tv_grantTime.setText(user.grantTime);
        tv_expireTime.setText(user.expireTime);

        et_pledgeNum.setText(user.pledgeNum);
        et_evaluationPrice.setText(user.evaluationPrice);
        et_companyName.setText(user.companyName);

        ViewUtil.setSpinnerSlection(user.companyType, getResources().getStringArray(R.array.sp_companyType), sp_companyType);
        et_loansPrice.setText(user.loansPrice);
        et_loansRate.setText(user.loansRate);
        tv_companyAddress.setText(user.companyAddress);
        et_companyAddressDetail.setText(user.companyAddressDetail);
        et_remark.setText(user.remark);

        tv_uid.setText(String.valueOf(uid));

    }



    @Override
    public void onClick(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.btn_borrowerProfilePic:
                // 跳转相册,选择图片 返回3
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                mResultLauncher.launch(intent);
                break;

            case R.id.iv_borrowerProfilePic:
                ViewUtil.showImageDialog(this, iv_borrowerProfilePic);
                break;


            case R.id.tv_borrowerSFZEndTime:
                showDateLimitPicker(true);
                break;

            case R.id.tv_creditTime:
                showDatePicker(this,tv_creditTime);
                break;

            case R.id.tv_grantTime:
                showDatePicker(this,tv_grantTime);
                break;

            case R.id.tv_expireTime:
                showDatePicker(this,tv_expireTime);
                break;

            case R.id.btn_save:
                saveUser();
                break;

            case R.id.iv_back:
                finish();
                break;

            case R.id.tv_borrowerHJAddress:
                chooseArea(JDCityConfig.ShowType.PRO_CITY,tv_borrowerHJAddress);
                break;

            case R.id.tv_guaranteeAddress:
                chooseArea(JDCityConfig.ShowType.PRO_CITY_DIS,tv_guaranteeAddress);
                break;
            case R.id.tv_companyAddress:
                chooseArea(JDCityConfig.ShowType.PRO_CITY_DIS,tv_companyAddress);
                break;

            case R.id.btn_navigation:
                jumpArea(tv_guaranteeAddress, et_guaranteeAddressDetail);
                break;

            case R.id.btn_navigation2:
                jumpArea(tv_companyAddress, et_companyAddressDetail);
                break;
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {//点击editText控件外部
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    assert v != null;
                    ViewUtil.hideOneInputMethod(this,v);
                    if (editText != null) {
                        editText.clearFocus();
                    }
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        return getWindow().superDispatchTouchEvent(ev) || onTouchEvent(ev);

    }

    EditText editText = null;

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            editText = (EditText) v;
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }

    private void jumpArea(TextView textView , EditText editTextDetails) {

        String address = (textView.getText().toString() + editTextDetails.getText().toString()).replaceAll(" - ", "").replaceAll("市辖区","");
        // ViewUtil.hideOneInputMethod(InsertOrEditActivity.this, et_borrowerPhone);
        DialogUtil.showMsgDialog(InsertOrEditActivity.this, "是否导航该地址", address  , null, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                boolean b = ViewUtil.isDownAndjumjp(InsertOrEditActivity.this, ViewUtil.GAODE_PACKAGENAME);
                if (!b) {
                    return;
                }
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                Log.d("tag", address);
                String s = "androidamap://keywordNavi?sourceApplication="+ViewUtil.getAppName(InsertOrEditActivity.this)+"&keyword="+address+"&style=2" ;
                // String s = "androidamap://poi?sourceApplication="+ViewUtil.getAppName(InsertOrEditActivity.this)+"&keywords="+address+"&dev=0" ;
                //androidamap://keywordNavi?sourceApplication=用户管理&keyword=江苏省南京市鼓楼区中山北路611号
                Log.d("tag", s);
                Uri uri = Uri.parse(s);
                intent.setData(uri);
                startActivity(intent);


            }
        });

    }

    private void chooseArea(JDCityConfig.ShowType showType,TextView textView) {

        ViewUtil.hideOneInputMethod(this,textView);
        cityPicker = new JDCityPicker();
        JDCityConfig jdCityConfig = new JDCityConfig.Builder().build();

        jdCityConfig.setShowType(showType);
        cityPicker.init(this);
        cityPicker.setConfig(jdCityConfig);
        cityPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                String text = "";
                if (StringUtils.isNotBlank(province.getName())) {
                    text += province.getName();
                }
                if (StringUtils.isNotBlank(city.getName())) {
                    text += " - "+city.getName();
                }
                if (StringUtils.isNotBlank(district.getName())) {
                    text += " - "+district.getName();
                }
                textView.setText(text);
            }

            @Override
            public void onCancel() {
            }
        });
        cityPicker.showCityPicker();
    }

    private void saveUser() {
        DialogUtil.showMsgDialog(this, "是否提交", "请确认是否填写完整", null, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                insertUser();
            }
        });

    }


    private void insertUser() {
        User user = new User();
        String text_uid = tv_uid.getText().toString();

        user.borrowerName = et_BorrowerName.getText().toString();
        user.borrowerSex = ViewUtil.getRGSelected(rg_borrowerSex).getTag().toString();
        user.borrowerPhone = et_borrowerPhone.getText().toString();
        user.borrowerSFZ = et_borrowerSFZ.getText().toString();
        user.borrowerSFZEndTime = tv_borrowerSFZEndTime.getText().toString();
        user.borrowerHJAddress = tv_borrowerHJAddress.getText().toString();
        user.borrowerHJType = ViewUtil.getRGSelected(rg_borrowerHJType).getTag().toString();

        user.borrowerProfilePic = FileUtils.FileSaveToInside(this, user.borrowerName + "_" + user.borrowerSFZ, ViewUtil.getBitmap(iv_borrowerProfilePic));

        user.spouseName = et_spouseName.getText().toString();
        user.spouseSFZ = et_spouseSFZ.getText().toString();
        user.suretyName = et_suretyName.getText().toString();
        user.suretyAge = et_suretyAge.getText().toString();
        user.suretySFZ = et_suretySFZ.getText().toString();
        user.guaranteeAddress = tv_guaranteeAddress.getText().toString();
        user.guaranteeAddressDetail = et_guaranteeAddressDetail.getText().toString();
        user.guaranteeArea = et_guaranteeArea.getText().toString();
        user.guaranteeCommoner = et_guaranteeCommoner.getText().toString();
        user.guaranteeYear = et_guaranteeYear.getText().toString();
        user.guaranteeType = sp_guaranteeType.getSelectedItem().toString();
        user.guaranteeQIUQUANHAO = et_guaranteeQIUQUANHAO.getText().toString();
        user.realEstateZJH = et_realEstateZJH.getText().toString();
        user.creditTime = tv_creditTime.getText().toString();
        user.grantTime = tv_grantTime.getText().toString();
        user.expireTime = tv_expireTime.getText().toString();
        user.pledgeNum = et_pledgeNum.getText().toString();
        user.evaluationPrice = et_evaluationPrice.getText().toString();
        user.companyName = et_companyName.getText().toString();
        user.companyType = sp_companyType.getSelectedItem().toString();
        user.loansPrice = et_loansPrice.getText().toString();
        user.loansRate = et_loansRate.getText().toString();
        user.companyAddress = tv_companyAddress.getText().toString();
        user.companyAddressDetail = et_companyAddressDetail.getText().toString();
        user.remark = et_remark.getText().toString();

        user.createTime = DateUtil.getNowTime();

        if (!StringUtils.isBlank(text_uid)) {
            user.uid = Integer.parseInt(text_uid);
            userDao.updateUser(user);
        } else {
            userDao.insertUser(user);
        }

        ToastUtil.show(this, "创建成功");

        Intent intent = new Intent();
        intent.setClass(this, MainActivity.class);
        startActivity(intent);

    }


    private void showDateLimitPicker(boolean isStartDate) {
        DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                Calendar selectedDate = Calendar.getInstance();
                selectedDate.set(year, month, dayOfMonth);

                if (isStartDate) {
                    String start = DateUtil.handleDate(selectedDate.get(Calendar.YEAR), selectedDate.get(Calendar.MONDAY) + 1, selectedDate.get(Calendar.DAY_OF_MONTH));
                    tv_borrowerSFZEndTime.setText(start);
                    showDateLimitPicker(false);
                } else {

                    String start = tv_borrowerSFZEndTime.getText().toString();
                    String end = DateUtil.handleDate(selectedDate.get(Calendar.YEAR), selectedDate.get(Calendar.MONDAY) + 1, selectedDate.get(Calendar.DAY_OF_MONTH));
                    tv_borrowerSFZEndTime.setText(start + " ~ " + end);
                }
            }
        };

        DatePickerDialog datePickerDialog = new DatePickerDialog(InsertOrEditActivity.this, DatePickerDialog.THEME_HOLO_LIGHT, dateSetListener, Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
        datePickerDialog.setTitle(isStartDate ? "开始日期" : "结束日期");
        datePickerDialog.show();

    }

    @Override
    public boolean onLongClick(View view) {
        switch (view.getId()) {
            case R.id.et_borrowerPhone:
                return callPhone();

        }

        return false;
    }

    private boolean callPhone() {
        ViewUtil.hideOneInputMethod(InsertOrEditActivity.this, et_borrowerPhone);
        DialogUtil.showMsgDialog(InsertOrEditActivity.this, "拨打电话", "是否拨打该电话: " + et_borrowerPhone.getText().toString(), null, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (permissionUtils.requesCallPhonePermissions(MY_PERMISSIONS_REQUEST_CALL_PHONE)) {
                    call();
                }
            }
        });
        return true;
    }
}